package com.heima.behavior.listener;

import com.heima.behavior.service.IApFollowBehaviorService;
import com.heima.common.util.JsonUtils;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Optional;

import static com.heima.common.constants.message.FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC;

@Slf4j
@Component
public class FollowBehaviorListener {

    @Autowired
    private IApFollowBehaviorService followBehaviorService;

    /**
     * 监听的方法，监听用户关注操作消息
     */
    @KafkaListener(topics = FOLLOW_BEHAVIOR_TOPIC)
    public void receiveMsg(ConsumerRecord<?,?> record){
        //校验消息是否有值
        Optional<? extends ConsumerRecord<?, ?>> optional = Optional.ofNullable(record);
        if(optional.isPresent()){
            //获取消息内容  json格式字符串
            Object value = record.value();
            //转为 FollowBehaviorDto 对象
            FollowBehaviorDto followBehaviorDto = JsonUtils.toBean(String.valueOf(value), FollowBehaviorDto.class);
            //记录关系行为
            followBehaviorService.saveFollowBehavior(followBehaviorDto);
        }
    }
}
